package com.cskaoyan.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问/user/hello ，在页面上出现hello world
 * 还有一个请求 /user/goodbye，在页面上出现 别了，司徒雷登
 * @author stone
 * @date 2022/11/14 14:19
 */
@WebServlet("/user/*")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        doService(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doService(req, resp);
        //doGet(req, resp);
    }

    private void doService(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //  /user/hello → sayHello
        //  /user/goodbye → sayGoodbye
        String requestURI = req.getRequestURI();
        String suffix = requestURI.replaceAll("/user/", "");
        if ("hello".equals(suffix)) {
            sayHello(resp);
        } else if ("goodbye".equals(suffix)) {
            sayGoodbye(resp);
        }

    }

    private void sayHello(HttpServletResponse resp) throws IOException {
        resp.getWriter().write("hello world");
    }
    private void sayGoodbye(HttpServletResponse resp) throws IOException {
        resp.getWriter().write("别了，司徒雷登");
    }
}
